<?php

use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use utils\out;

function getRandId() {
    //新时间截定义,基于世界未日2012-12-21的时间戳。
    $endtime=1356019200;//2012-12-21时间戳
    $curtime=time();//当前时间戳
    $newtime=$curtime-$endtime;//新时间戳
    $rand=rand(0,999);//两位随机
    $all=$rand.$newtime;
    $onlyid=base_convert($all,10,36);//把10进制转为36进制的唯一ID
    return $onlyid;
}

/**菜单列表*/
$app->get('/bd/menu', function (Application $app, Request $request) {
	if(!$_SESSION || !$_SESSION['userinfo']) {
		return $app->redirect('/login');
	}
	$limit = 20;
	$page = $request->get('page');
	if (!$page) {
        $page = 1;
    }
	$start = ($page - 1) * $limit;

	$sql = "SELECT id, title, thumbnail, createdAt, modifiedAt, isDeleted, status, rank, isRecommend FROM t_menu WHERE isDeleted = 0 ORDER BY createdAt DESC LIMIT $start, $limit";
	$data = $app['db']->fetchAll($sql);

	for($i=0; $i<count($data); $i++) {
		$data[$i]['modifiedAt'] =date("Y-m-d H:i", $data[$i]['modifiedAt']);
	}

	return $app['twig']->render('bd_menu_list.html', array('result'=>$data, 'page'=>$page));
});


/**添加菜单*/
$app->get('/bd/menu/add', function (Application $app) {
	if(!$_SESSION || !$_SESSION['userinfo']) {
		return $app->redirect('/login');
	}

	return $app['twig']->render('bd_menu_form.html', array("id"=>0));
});


/**编辑菜单*/
$app->get('/bd/menu/{id}', function (Application $app, $id) {
	if(!$_SESSION || !$_SESSION['userinfo']) {
		return $app->redirect('/login');
	}
	return $app['twig']->render('bd_menu_form.html', array("id"=>$id));
});


/**菜单详情*/
$app->get('/bd/menu/{id}/data', function (Application $app, $id) {
	if(!$_SESSION || !$_SESSION['userinfo']) {
		return $app->redirect('/login');
	}
	$sql = "SELECT * FROM t_menu WHERE isDeleted = 0 AND id = ?";
	$data = $app['db']->fetchAssoc($sql, array((int) $id));
	return $app->json(array("success"=>true, "result"=>$data));
});


/**添加菜单*/
$app->post('/bd/menu', function (Application $app, Request $request) {

    $thumbnailW = 600;
    $thumbnailH = 400;

	if(!$_SESSION || !$_SESSION['userinfo']) {
		return $app->redirect('/login');
	}

	$title = $request->get('title');
	$summary = $request->get('summary');
	$content = $request->get('content');
	$status = $request->get('status');
	$thumbnail = $_FILES["thumbnail"];
	$main = $request->get('main');
    $assist = $request->get('assist');
    $isRecommend = $request->get('isRecommend') == 1;

	if(!$title || !$content || !$thumbnail || !$main || !$assist) {
		return $app->json(array("success"=>false, "result"=>"却少参数"));
	}

	$relativePath = '';

	if ((($_FILES["thumbnail"]["type"] == "image/gif")
		|| ($_FILES["thumbnail"]["type"] == "image/jpeg")
		|| ($_FILES["thumbnail"]["type"] == "image/pjpeg"))
		|| ($_FILES["thumbnail"]["type"] == "image/png")) { 

		if ($_FILES["thumbnail"]["error"] > 0) {
		  	return $app->json(array("success"=>false, "result"=>"error|" . $_FILES["thumbnail"]["error"]));
		} else {

		    // 检查图片尺寸
            $imageSize = getimagesize($_FILES["thumbnail"]['tmp_name']);
            if($imageSize[0] != $thumbnailW || $imageSize[1] != $thumbnailH) {
                return $app->json(array("success"=>false, "result"=>"图片尺寸需限制为:".$thumbnailW. 'x'. $thumbnailH ));
            }

	   		if ($_FILES["thumbnail"]["size"] > 1000*1024) {// 1M
	   			return $app->json(array("success"=>false, "result"=>"error|图片大小不能大于1M"));
	   		}

	   		$fileName = $_FILES["thumbnail"]["name"];
	   		$tmp = explode(".", $fileName);
	   		$suffix = '';
	   		if(count($tmp) > 1) {
	   			$suffix = '.' . $tmp[count($tmp)-1];
	   		}
	   		$fileName = getRandId() . $suffix;

	   		// detect if make dir
	   		$format = date('Y/m/d');
	   		$relativePath = "/files/upload/$format";
	   		$fileAbsolutePath = $_SERVER['DOCUMENT_ROOT'] . $relativePath;
	   		if(!file_exists($fileAbsolutePath)) {
	   			mkdir($fileAbsolutePath, 0777, true);
	   		}

	   		$fileAbsolutePath = $fileAbsolutePath . '/' . $fileName;
		    move_uploaded_file($_FILES["thumbnail"]["tmp_name"], $fileAbsolutePath);

		    $relativePath = $relativePath . '/' . $fileName;
		}
	} else {
	  	return $app->json(array("success"=>false, "result"=>"error|不支持的文件类型"));
	}

	if($isRecommend == 1) {
	    // 删除其他推荐
        $sql = "UPDATE t_menu set isRecommend=0 where isRecommend=1";
        $app['db']->executeUpdate($sql);
	}

	$sql = "INSERT INTO t_menu(title,thumbnail,createdAt,modifiedAt,isDeleted,status,summary,content,main,assist,rank,viewCount,praiseCount,isRecommend) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
	$data = $app['db']->executeUpdate($sql, array(
			$title,
			$relativePath,
			time(),
			time(),
			false,
			$status,
			$summary,
			$content,
			$main,
			$assist,
			0,
			0,
			0,
			$isRecommend
		));
	return $app->json(array("success"=>true, "result"=>"ok"));
});


/**修改菜单*/
$app->post('/bd/menu/{id}', function (Application $app, Request $request, $id) {
    $thumbnailW = 600;
    $thumbnailH = 400;

	if(!$_SESSION || !$_SESSION['userinfo']) {
		return $app->redirect('/login');
	}

	$title = $request->get('title');
	$summary = $request->get('summary');
	$content = $request->get('content');
	$status = $request->get('status');
	$main = $request->get('main');
    $assist = $request->get('assist');
    $isRecommend = (int)$request->get('isRecommend');

	if(!$title || !$content || !$main || !$assist) {
        return $app->json(array("success"=>false, "result"=>"却少参数"));
    }

	$relativePath = '';
	if(isset($_FILES["thumbnail"]) && $_FILES["thumbnail"]["size"] > 0) {
		if (($_FILES["thumbnail"]["type"] == "image/gif")
			|| ($_FILES["thumbnail"]["type"] == "image/jpeg")
			|| ($_FILES["thumbnail"]["type"] == "image/pjpeg")
			|| ($_FILES["thumbnail"]["type"] == "image/png")) { 

			if ($_FILES["thumbnail"]["error"] > 0) {
			  	return $app->json(array("success"=>false, "result"=>"error|" . $_FILES["thumbnail"]["error"]));
			} else {

            	// 检查图片尺寸
            	$imageSize = getimagesize($_FILES["thumbnail"]['tmp_name']);
            	if($imageSize[0] != $thumbnailW || $imageSize[1] != $thumbnailH) {
            	    return $app->json(array("success"=>false, "result"=>"图片尺寸需限制为:".$thumbnailW. 'x'. $thumbnailH ));
                }

		   		if ($_FILES["thumbnail"]["size"] > 1000*1024) {// 1M
		   			return $app->json(array("success"=>false, "result"=>"error|图片大小不能大于1M"));
		   		}

		   		$fileName = $_FILES["thumbnail"]["name"];
		   		$tmp = explode(".", $fileName);
		   		$suffix = '';
		   		if(count($tmp) > 1) {
		   			$suffix = '.' . $tmp[count($tmp)-1];
		   		}
		   		$fileName = getRandId() . $suffix;

		   		// detect if make dir
		   		$format = date('Y/m/d');
		   		$relativePath = "/files/upload/$format";
		   		$fileAbsolutePath = $_SERVER['DOCUMENT_ROOT'] . $relativePath;
		   		if(!file_exists($fileAbsolutePath)) {
		   			mkdir($fileAbsolutePath, 0777, true);
		   		}

		   		$fileAbsolutePath = $fileAbsolutePath . '/' . $fileName;
			    move_uploaded_file($_FILES["thumbnail"]["tmp_name"], $fileAbsolutePath);

			    $relativePath = $relativePath . '/' . $fileName;
			}
		} else {
		  	return $app->json(array("success"=>false, "result"=>"error|不支持的文件类型"));
		}
	} else {
	    $relativePath = $request->get('thumbnail_org');
	}

    if($isRecommend == 1) {
	    // 删除其他推荐
        $sql = "UPDATE t_menu set isRecommend=0 where isRecommend=1";
        $app['db']->executeUpdate($sql);
	}

	// 更新
    $sql = "UPDATE t_menu set title=?,thumbnail=?,modifiedAt=?,status=?,summary=?,content=?,main=?,assist=?,isRecommend=$isRecommend where id=?";
    $app['db']->executeUpdate($sql, array(
            $title,
            $relativePath,
            time(),
            $status,
            $summary,
            $content,
            $main,
            $assist,
            $id
        ));
	return $app->json(array("success"=>true, "result"=>"ok"));
});


/**删除菜单*/
$app->delete('/bd/menu/{id}', function (Application $app, Request $request, $id) {
	if(!$_SESSION || !$_SESSION['userinfo']) {
		return $app->redirect('/login');
	}

	$sql = "UPDATE t_menu SET isDeleted=1 WHERE id = ?";
	$data = $app['db']->executeUpdate($sql, array($id));

	return $app->json(array("success"=>true, "result"=>"ok"));
});
